import { ref, toRefs } from "vue"
import Query from "../../../zondy/lib/Query.js"
import createDraw from "../../../zondy/lib/draw.js"
import { useMapStore } from "../../store/useMap.js"
const { mapState } = toRefs(useMapStore())
export const useRectangleEvent = () => {
  const draw = ref(null)
  const rectanglesource = ref(null)
  const rectanglelayer = ref(null)
  const rectangleService = { name: "traffic", layerId: 2 }
  const rectangleEventData = ref([])
  const rectangleEventFID = []
  rectanglesource.value = new ol.source.Vector({ wrapX: false })
  rectanglelayer.value = new ol.layer.Heatmap({
    source: rectanglesource.value,
  })
  function queryByRectangle() {
    mapState.value.map.addLayer(rectanglelayer.value)
    draw.value = createDraw({ source: rectanglesource.value, type: "Box" })
    mapState.value.map.addInteraction(draw.value)
    draw.value.on("drawend", endDraw, this)
  }
  function endDraw(e) {
    mapState.value.map.removeInteraction(draw.value)
    Query.queryByGeom({ geometry: e.feature.getGeometry(), service: rectangleService, success: rectangleSuccess })
  }
  function rectangleSuccess(e) {
    mapState.value.dialogTableVisible = true
    rectangleEventData.value = []
    e.SFEleArray.forEach(item => {
      rectangleEventFID.push(item.FID)
    })
    var format = new Zondy.Format.PolygonJSON()
    /* 将mapgis要素json反序列化为ol.feature类型数组 */
    var features = format.read(e)
    /* 将查询到的要素添加到高亮图层中 */
    features.forEach(item => {
      rectangleEventData.value.push(item.values_.values_)
    })
    for (let i = 0; i < rectangleEventData.value.length; i++) {
      rectangleEventData.value[i].FID = rectangleEventFID[i]
    }
    mapState.value.eventData = rectangleEventData.value
    mapState.value.map.removeLayer(rectanglelayer.value)
  }
  return { queryByRectangle }
}
